<template>
  <div class="cart-add">
    <h2>添加图书到购物车</h2>
    
    <el-form :model="form" label-width="120px">
      <el-form-item label="图书ID">
        <el-input v-model="form.bookId" disabled />
      </el-form-item>
      <el-form-item label="数量">
        <el-input-number v-model="form.quantity" :min="1" :max="100" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">添加到购物车</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const form = ref({
  bookId: Number(route.params.bookId),
  quantity: 1
})

const handleSubmit = async () => {
  try {
    await request.post(`/user/cart/add/${form.value.bookId}`, {
      quantity: form.value.quantity
    })
    ElMessage.success('添加成功')
    router.push({ name: 'CartList' })
  } catch (error) {
    ElMessage.error('添加失败')
  }
}

const handleCancel = () => {
  router.go(-1)
}
</script>

<style scoped>
.cart-add {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
</style>